<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    .photo {
      inset: 0;
      margin: auto;
      width: 500px;
      height: 500px;
      position: absolute;
    }
    img {
      width: 500px;
      border-radius: 10px;
    }
  </style>
  <body>
    <div class="photo">
      <img alt="只是一张背景图" class="maskPic" />
    </div>
  </body>
  <script>
    const bgImg =
      "https://img2.baidu.com/it/u=2243573419,589412055&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500";
    const maskImg = "https://files.catbox.moe/dlteg1.png";
    async function init() {
      const img = await addMask(bgImg);
      document.querySelector(".maskPic").setAttribute("src", img);
    }
    window.onload = init();
    // 获取图片的Base64编码
    function getBase64(base64, width = 50) {
      console.log(width);
      const picture = new Image();
      picture.src = base64;
      picture.setAttribute("crossOrigin", "Anonymous");
      return new Promise((resolve, reject) => {
        picture.onload = () => {
          const canvas = document.createElement("canvas");
          const context = canvas.getContext("2d");
          canvas.width = width + 70;
          canvas.height = (picture.height * width) / picture.width + 40;
          context.fillRect(0, 0, canvas.width, canvas.height);
          context.drawImage(picture, 0, 0, canvas.width, canvas.height);
          resolve(canvas.toDataURL("image/jpeg"));
        };
      });
    }

    // 加水印事件
    function addMask(base64) {
      const maskPic = new Image();
      maskPic.src = base64;
      maskPic.setAttribute("crossOrigin", "Anonymous");
      return new Promise((resolve, reject) => {
        maskPic.onload = async () => {
          const canvas = document.createElement("canvas");
          const context = canvas.getContext("2d");
          canvas.width = maskPic.width;
          canvas.height = maskPic.height;
          context.fillRect(0, 0, canvas.width, canvas.height);
          context.drawImage(maskPic, 0, 0, canvas.width, canvas.height);
          const waterMarkSrc = await getBase64(maskImg, 100);
          const waterMarkImg = new Image();
          waterMarkImg.src = waterMarkSrc;
          waterMarkImg.setAttribute("crossOrigin", "Anonymous");
          waterMarkImg.onload = () => {
            context.drawImage(
              waterMarkImg,
              680,
              canvas.height - 450,
              waterMarkImg.width,
              waterMarkImg.height
            );
            resolve(canvas.toDataURL("image/jpeg"));
          };
        };
      });
    }
  </script>
</html>
